package cn.kgc.crowdfundingadminspringboot.controller;

import cn.kgc.crowdfundingadminspringboot.common.CrowdFundingConstant;
import cn.kgc.crowdfundingadminspringboot.pojo.Admin;
import cn.kgc.crowdfundingadminspringboot.service.AdminService;

import com.github.pagehelper.PageInfo;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
public class AdminController {
	
	@Resource
	AdminService adminService;
	
	@GetMapping("/getbyid/{id}")
	public Admin getById(@PathVariable Integer id){
		return adminService.selectByPrimaryKey(id);
	}
	
	//登录页面控制器
	@RequestMapping("/admin/to/login/page.html")
	public String toLoginPage() {
		return "admin-login";
	}
	
	/**
	 * 跳转后台主页面
	 * @return
	 */
	@RequestMapping("/admin/to/main/page.html")
	public String toLogin(){
		return "admin-main";
	}
	/**
	 * 登录
	 */
	@RequestMapping("/admin/do/login")
	public String doLogin(
			@RequestParam("loginAcct") String loginAcct,
			@RequestParam("userPswd") String userPswd,
			Model model,
			HttpSession session){
		Admin admin = adminService.login(loginAcct, userPswd);
		if (admin==null){
			//登陆失败
			model.addAttribute(CrowdFundingConstant.ATTR_NAME_MESSAGE, CrowdFundingConstant.MESSAGE_LOGIN_FAILED);
			return "admin-login";
		}
		session.setAttribute(CrowdFundingConstant.ATTR_NAME_LOGIN_ADMIN, admin);
		return "redirect:/admin/to/main/page.html";
	}
	
	
	//处理登录
	@RequestMapping("/do/login")
	public String doLogin(String loginAcct,
	                      String userPswd,
	                      HttpSession session,
	                      Model model){
		Admin admin = adminService.login(loginAcct, userPswd);
		if (admin==null){
			//登录失败
			model.addAttribute("MESSAGE","登录账号或密码不正确！请核对后再登录！");
			return "admin-login";
		}
		
		session.setAttribute("LOGIN-ADMIN",admin);
		return "admin-main";
	}
	
	//退出登录操作
	@RequestMapping("/admin/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/index";
	}
	
	
	//局部异常处理
	@ExceptionHandler(value=Exception.class)
	public String catchException(Exception exception,Model model) {
		model.addAttribute(CrowdFundingConstant.ATTR_NAME_ERROR_MESSAGE, exception.getMessage());
		return "system-error";
	}
	
	/**
	 * 查询用户
	 * @param pageNum
	 * @param pageSize
	 * @param keyword
	 * @param model
	 * @return
	 */
	@RequestMapping("/admin/query/for/search")
	public String queryForSearch(
			
			// 如果页面上没有提供对应的请求参数，那么可以使用defaultValue指定默认值
			@RequestParam(value="pageNum", defaultValue="1") Integer pageNum,
			@RequestParam(value="pageSize", defaultValue="5") Integer pageSize,
			@RequestParam(value="keyword", defaultValue="") String keyword,
			Model model) {
		
		PageInfo<Admin> pageInfo = adminService.queryForKeywordSearch(pageNum, pageSize, keyword);
		
		model.addAttribute(CrowdFundingConstant.ATTR_NAME_PAGE_INFO, pageInfo);
		
		return "admin-page";
	}
	
	
}
